<?php

namespace app\checkin\controller;

use think\admin\Controller;
use think\facade\Session;
use app\checkin\model\Member as MemberModel;
use app\checkin\model\CheckinRecord as RecordModel;
use app\checkin\model\Gift as GiftModel;

/**
 * H5 前台页面（会员登录/查询）
 */
class H5 extends Controller
{
    /**
     * 登录页 & 登录提交
     * @login false
     * @menu false
     */
    public function login()
    {
        $this->title = '会员登录';
        if ($this->request->isGet()) {
            return $this->fetch();
        }
        // POST 登录（手机号 + 密码）
        $phone = trim(strval($this->request->post('phone', '')));
        $pass  = strval($this->request->post('password', ''));
        if ($phone === '' || $pass === '') {
            $this->assign('error', '请输入手机号与密码');
            return $this->fetch();
        }
        $member = MemberModel::mk()->where(['phone' => $phone])->findOrEmpty();
        if ($member->isEmpty()) {
            $this->assign('error', '账号或密码不正确');
            return $this->fetch();
        }
        if (intval($member->getAttr('status')) !== 1) {
            $this->assign('error', '会员状态异常，无法登录');
            return $this->fetch();
        }
        $stored = strval($member->getAttr('password') ?? '');
        $ok = false;
        if ($stored !== '') {
            if (stripos($stored, '$2y$') === 0 || stripos($stored, '$argon2') === 0) {
                // 已加密存储（bcrypt/argon2）
                $ok = password_verify($pass, $stored);
            } else {
                // 明文存储
                $ok = hash_equals($stored, $pass);
            }
        }
        if (!$ok) {
            $this->assign('error', '账号或密码不正确');
            return $this->fetch();
        }
        Session::set('member', [
            'id' => intval($member->getAttr('id')),
            'name' => strval($member->getAttr('name')),
            'phone' => strval($member->getAttr('phone')),
        ]);
        return redirect(sysuri('center'));
    }

    /**
     * 退出登录
     * @login false
     * @menu false
     */
    public function logout()
    {
        Session::delete('member');
        return redirect(sysuri('login'));
    }

    /**
     * 会员中心（积分概览）
     * @login false
     * @menu false
     */
    public function center()
    {
        $m = $this->getLoginMember();
        $member = MemberModel::mk()->where(['id' => $m['id']])->findOrEmpty();
        if ($member->isEmpty()) return redirect(sysuri('logout'));
        $this->assign('member', $member->toArray());
        return $this->fetch();
    }

    /**
     * 我的打卡记录
     * @login false
     * @menu false

     */

    /**
     * 修改密码（需登录）
     * @login false
     * @menu false
     */
    public function password()
    {
        $m = $this->getLoginMember();
        if ($this->request->isGet()) {
            return $this->fetch();
        }
        $old = strval($this->request->post('old_password', ''));
        $new = strval($this->request->post('new_password', ''));
        $rep = strval($this->request->post('re_password', ''));
        if ($old === '' || $new === '' || $rep === '') {
            $this->assign('error', '请完整填写原密码与新密码');
            return $this->fetch();
        }
        if ($new !== $rep) {
            $this->assign('error', '两次输入的新密码不一致');
            return $this->fetch();
        }
        if (strlen($new) < 6) {
            $this->assign('error', '新密码至少 6 位');
            return $this->fetch();
        }
        $member = MemberModel::mk()->where(['id' => $m['id']])->findOrEmpty();
        if ($member->isEmpty()) {
            return redirect(sysuri('logout'));
        }
        $stored = strval($member->getAttr('password') ?? '');
        $ok = false;
        if ($stored !== '') {
            if (stripos($stored, '$2y$') === 0 || stripos($stored, '$argon2') === 0) {
                $ok = password_verify($old, $stored);
            } else {
                $ok = hash_equals($stored, $old);
            }
        }
        if (!$ok) {
            $this->assign('error', '原密码不正确');
            return $this->fetch();
        }
        $hash = password_hash($new, PASSWORD_BCRYPT);
        $member->save(['password' => $hash]);
        // 更新 Session 中信息（不含密码）
        Session::set('member', [
            'id' => intval($member->getAttr('id')),
            'name' => strval($member->getAttr('name')),
            'phone' => strval($member->getAttr('phone')),
        ]);
        return redirect(sysuri('center'));
    }

    /**
     * 设置/找回密码（未登录，通过 手机号+卡号 校验）
     * @login false
     * @menu false
     */
    public function reset()
    {
        if ($this->request->isGet()) {
            return $this->fetch();
        }
        $phone = trim(strval($this->request->post('phone', '')));
        $card  = trim(strval($this->request->post('card_no', '')));
        $pass  = strval($this->request->post('password', ''));
        $rep   = strval($this->request->post('re_password', ''));
        if ($phone === '' || $card === '' || $pass === '' || $rep === '') {
            $this->assign('error', '请完整填写手机号、卡号与新密码');
            return $this->fetch();
        }
        if ($pass !== $rep) {
            $this->assign('error', '两次输入的新密码不一致');
            return $this->fetch();
        }
        if (strlen($pass) < 6) {
            $this->assign('error', '新密码至少 6 位');
            return $this->fetch();
        }
        $member = MemberModel::mk()->where(['phone' => $phone, 'card_no' => $card])->findOrEmpty();
        if ($member->isEmpty()) {
            $this->assign('error', '手机号或卡号不正确');
            return $this->fetch();
        }
        if (intval($member->getAttr('status')) !== 1) {
            $this->assign('error', '会员状态异常，无法设置密码');
            return $this->fetch();
        }
        $hash = password_hash($pass, PASSWORD_BCRYPT);
        $member->save(['password' => $hash]);
        return redirect(sysuri('login'));
    }

    public function records()
    {
        $m = $this->getLoginMember();
        $list = RecordModel::mk()->where(['member_id' => $m['id']])
            ->with(['store']) // 关联加载门店信息
            ->order('create_time desc')->limit(50)->select()->toArray();
        $this->assign('list', $list);
        return $this->fetch();
    }

    /**
     * 查看积分礼品（仅展示）
     * @login false
     * @menu false
     */
    public function gifts()
    {
        $this->getLoginMember(); // 需登录
        $gifts = GiftModel::mk()->where(['status' => 1])->order('sort desc,id desc')->select()->toArray();
        $this->assign('gifts', $gifts);
        return $this->fetch();
    }

    // ============== helper ==============
    private function getLoginMember(): array
    {
        $m = Session::get('member');
        if (!$m || empty($m['id'])) {
            if ($this->request->isAjax()) $this->error('请先登录', sysuri('login'));
            redirect(sysuri('login'))->send(); exit;
        }
        return $m;
    }
}

